package com.dctp.ems.controller;

import com.dctp.common.cache.RoleCache;
import com.dctp.common.controller.BaseController;
import com.dctp.common.utils.DateUtil;
import com.dctp.common.vo.JsonResult;
import com.dctp.common.vo.PageResult;
import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色管理
 *
 * basePath: /role
 * 前端字段名已与数据库列名保持一致
 */
@Path("/dctpRole")
public class RoleController extends BaseController {

    /* ---------------- 分页查询 ---------------- */
    public void list() {

        int page     = getInt("currentPage", 1);
        int pageSize = getInt("pageSize", 10);
        String name  = getPara("name",  "");
        String code  = getPara("code",  "");
        String status= getPara("status","");

        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object>  ps    = new ArrayList<>();
        if (StrKit.notBlank(name))   { where.append("AND name LIKE ? ");  ps.add('%'+name+'%'); }
        if (StrKit.notBlank(code))   { where.append("AND code LIKE ? ");  ps.add('%'+code+'%'); }
        if (StrKit.notBlank(status)) { where.append("AND status = ? ");   ps.add(status); }

        var p = Db.paginate(page, pageSize,
                "SELECT * ",
                "FROM dctp_role "+where+" ORDER BY id ASC",
                ps.toArray());
        renderJson(JsonResult.successWithData(
            new PageResult<>(p.getList(), p.getTotalRow(), pageSize, page)
        ));
    }

    /* ---------------- 新增角色 ---------------- */
    @Before(Tx.class)
    public void add() {

        Record body = jsonBody();  // 字段与表一致
        if (StrKit.isBlank(body.getStr("name")) ||
            StrKit.isBlank(body.getStr("code"))) {
            renderJson(JsonResult.failWithMessage("name 与 code 均不能为空"));
            return;
        }

        Long exist = Db.queryLong("SELECT 1 FROM dctp_role WHERE code=? LIMIT 1",
                                  body.getStr("code"));
        if (exist != null) {
            renderJson(JsonResult.failWithMessage("code 已存在"));
            return;
        }

        body.set("create_time", DateUtil.now());

        if (!Db.save("dctp_role", body))
            throw new RuntimeException("新增角色失败");

        renderJson(JsonResult.success());
    }

    /* ---------------- 修改角色 ---------------- */
    @Before(Tx.class)
    public void update() {

        Long id = getParaToLong(0);
        if (id == null) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }

        Record body = jsonBody();
        if (body.getColumns().isEmpty()) {
            renderJson(JsonResult.failWithMessage("无有效字段"));
            return;
        }

        body.set("id", id)
            .set("update_time", DateUtil.now());

        if (!Db.update("dctp_role", body))
            throw new RuntimeException("角色不存在或已删除");

        //删除缓存
        RoleCache.delete(id);
        renderJson(JsonResult.success());
    }

    /* ---------------- 删除角色 ---------------- */
    @Before(Tx.class)
    public void delete() {

        Long id = getParaToLong(0);
        if (id == null) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }

        int n = Db.update("DELETE FROM dctp_role WHERE id=?", id);
        if (n == 0) throw new RuntimeException("角色不存在或已删除");

        RoleCache.delete(id);
        renderJson(JsonResult.success());
    }

    /* ---------------- 启用角色列表 ---------------- */
    public void all() {
        List<Record> rows = Db.find("SELECT id,name,level,code FROM dctp_role WHERE status=1");
        renderJson(JsonResult.successWithData(rows));
    }
}
